<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>copy</title>
	</head>

	<body>
		<p type="text" id="text">111</p>
		<button id="btn" onclick="copy()">点击</button>
		<script>
			function copy() {
				const selection = window.getSelection();
				const range = document.createRange();

				// RangeAPI: 制造区域
				range.selectNodeContents(document.querySelector('#text'));

				// Selection: 选中区域
				selection.addRange(range);

				// selectedText = selection.toString(); // 选中的文本

				try {
					let isSuccess = document.execCommand('copy'); // 复制
				} catch {
					console.log('Oops, unable to copy');
				}

				// 移除选中
				selection.removeAllRanges(); // 清除选中区域
			}
		</script>
	</body>
</html>
